import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { logIn, updatePassword, logOut } from '@/api/system'
import { ElLoading, ElMessageBox,ElMessage } from 'element-plus'
import router from '@/router/index'

export const useUserStore = defineStore('user', () => {
  const loadingInstance = ref(null)
  const userInfo = ref({
    userName: '',
    authority: '',
    phone: '',
    activeColor: 'var(--el-color-primary)',
    baseColor: '#fff',
    sideMode: 'dark'
  })

  const token = ref(localStorage.getItem('token'))

  /* 登录*/
  const LoginIn = async(loginInfo) => {
    loadingInstance.value = ElLoading.service({
      fullscreen: true,
      text: '登录中，请稍候...',
    })
    try {
      const res = await logIn(loginInfo)
      if (res.errcode === 0) {
        setUser(loginInfo)
        setToken(res.content.token)
        setExpire(res.content.token_expire)
        loadingInstance.value.close()
        ElMessage({
          message: res.message,
          type: 'success',
        })
        router.push({ name: 'Boards' })
        location.reload()
      }
    } catch (e) {
      loadingInstance.value.close()
    }
    loadingInstance.value.close()
  }

  // 修改密码
  const ChangePassword = async(params) => {
    const res = await updatePassword(params)
    ElMessageBox.alert(res.msg)
  }

  // 退出登录
  const LogOut = async() => {
    await ClearStorage()
    localStorage.removeItem('token')
    router.push({ name: 'Login' })
  }

  const setToken = (val) => {
    token.value = val
    localStorage.setItem('token', val)
  }

  const setExpire = (val) => {
    localStorage.setItem('expireTime', val)
  }

  const setUser = (val) => {
    userInfo.value.userName = val.UserName
    userInfo.value.authority = val.UserName
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  /* 清理数据 */
  const ClearStorage = async() => {
    token.value = ''
    sessionStorage.clear()
    window.localStorage.removeItem('token')
  }

  /* 设置侧边栏模式*/
  const sideMode = computed(() => {
    if (userInfo.value.sideMode === 'dark') {
      return '#191a23'
    } else if (userInfo.value.sideMode === 'light') {
      return '#fff'
    } else {
      return userInfo.value.sideMode
    }
  })

  const baseColor = computed(() => {
    if (userInfo.value.sideMode === 'dark') {
      return '#fff'
    } else if (userInfo.value.sideMode === 'light') {
      return '#191a23'
    } else {
      return userInfo.value.baseColor
    }
  })
  const activeColor = computed(() => {
    return 'var(--el-color-primary)'
  })

  return {
    userInfo,
    token,
    LoginIn,
    ClearStorage,
    setToken,
    ChangePassword,
    LogOut,
    sideMode,
    baseColor,
    activeColor
  }
})

